class MyDataHandler {
  constructor(options, dataInfo) {

    let scoreNames = dataInfo.scoreNames;

    let teamCols = dataInfo.teamCols;
    let areas = dataInfo.areas;
    let areaEns = dataInfo.areaEns;
    let errorList = [];
    let myData = {};


    function reportError(name, pos, error, type = "error") {
      errorList.push({ name, pos, error, type });
    }

    function getStudentScore(student) {
      let score = 0;
      (scoreNames||[]).forEach(k=>{
        score += toNumber(student[k]);
      });      
      return toNumber(toRoundFixed(score));
    }


    /**
     * 团队总分：3-6人团队，取前三名成绩加和，21000分
     * @param v
     */
    function getTeamScore(v) {
      let items = (v["items"] || []).sortByLimit(["StudentScore desc"], 3);
      let score = 0;
      items.forEach(item => score += toNumber(item["StudentScore"]));
      return toNumber(toRoundFixed((score)));

    }

    function initStudent(excelData = {}) {
      let isReadStudentScore = options.isReadStudentScore || false;
      let studentList = excelData["student"];
      studentList = studentList.sortBy(["Division"]);
      (studentList || []).forEach(item => {
        if (!isReadStudentScore) {
          item["StudentScore"] = getStudentScore(item);
          delete item["_null_StudentScore"];
        }
        item["Score"] = item["StudentScore"];
        item["Name"] = item["StudentName"] || (item["FirstName"] + " " + item["LastName"]);
        item["Names"] = item["Name"];
        item["_id"] = item["UserID"];
        item["id"] = item["_id"];
        item["SchoolRegionEn"] = areaEns[item["SchoolRegion"]];
        if (dataInfo.studentHandler){
          dataInfo.studentHandler(item);
        }
      });
      myData["student"] = studentList || [];
      // myData["student.rookie"] = studentList.filter(item => item.Rookie == 1);
    }

    function initTeam() {

      let studentList = myData["student"] || [];
      let teamList = studentList.groupBy("TeamNumber");
      let isReadTeamScore = options.isReadTeamScore || false;
      (teamList || []).forEach(v => {
        try {
          let firstItem = v["items"][0];

          teamCols.forEach(name => {
            v[name] = firstItem[name];
          });
          v["Name"] = firstItem["School_Cn"] + "(" + firstItem["TeamNumber"] + ")";
          v["Names"] = v["items"].map((item) => item.FirstName + " " + item.LastName).join(" / ");
          v["_id"] = firstItem["TeamNumber"];
          v["id"] = v["_id"];          
          if (!isReadTeamScore) {
            v["TeamScore"] = getTeamScore(v);
            (v["items"] || []).forEach(student => {
              student["TeamScore"] = v["TeamScore"]
              student["TeamNames"] = v["Names"];
            });
          }
          v["Score"] = v["TeamScore"];

          if (dataInfo.teamHandler){
            dataInfo.teamHandler(v);
          }

        } catch (e) {
          reportError("Student", 0, "初始化团队数据时异常,error:" + e.message);
        }

      });
      // myData["team.rookie"] = teamList.filter(item => item.Rookie == 1);
      myData["team"] = teamList;

    }

    function initTeamTop(){
      let teamList = myData["team"];
      let teamTop = [];
      teamList.forEach(v=>{
        let itemTop = (v["items"] || []).sortByLimit(["StudentScore desc"], 1);
        teamTop.push(...itemTop);
      })
      myData["student.队内最高分"] = teamTop;
      
    }



    function initMyAreaData() {
      let splitData = (key) => {
        (areas || []).forEach(area => {
          let items = (myData[key] || []).filter(t => t.SchoolRegion == area);
          myData[key + "." + area] = items;
        });
        // let gs = (myData[key] || []).groupBy("SchoolRegion");
        // (gs || []).forEach(g => {
        //   myData[key + "." + g.key["SchoolRegion"]] = g.items;
        // })
      };
      splitData("student");
      splitData("team");
    }


    this.getMyData = function (excelData) {
      myData = {};
      errorList = [];
      initStudent(excelData);
      initTeam();
      initTeamTop();
      initMyAreaData();
      if (dataInfo.myDataHandler){
        errorList.push(...dataInfo.myDataHandler(excelData,myData));
      }
      return [myData, errorList];
    };

  }
}
